# 订单管理
class Api::OrdersController < Api::BaseController

	skip_before_filter :valid_permission, only: [:update_estimated_total, :update_rebate, :fetch_users]
	before_filter :get_order, only: [:update_estimated_total, :update_rebate]

	# 订单列表
	# 
	# Params
	# 	access_token: [String] authenication_token
	# 	type: [String] children
	#   category: [String] pre_completed|completed, default is all
	#   q: [String] 查询关键字
	#   page: [Integer] 页码
	# Return
	# 	status: [String] success
	#   list: [Hash] orders list
	#   total: [Integer] 总数
	# Error
	#   status: [String] failed
	def index
		extra_info = [:user, :customer, :_region, :store, :strategy_result]
		
		conds = {}

		if @current_user.role == 'saler_director' && params[:type] == 'children'
			conds[:user_id] = @current_user.children.map(&:id)
		elsif @current_user.role == 'admin' && params[:type] == 'children'
			conds[:account_id] = @account.id
		else
			conds[:user_id] = @current_user.id
		end

		if params[:q]
			c_ids = @current_user.customers.ransack('tel_or_name_cont' => params[:q]).result.map(&:id)
      orders = Order.includes(extra_info).where(conds).where("serial_number like ? or customer_id in (?)", "%#{params[:q]}%", c_ids).order(updated_at: :desc).page(params[:page]).per(params[:limit])
		elsif ['pre_completed', 'completed'].include?(params[:category])
      orders = Order.includes(extra_info).send(params[:category].to_sym).where(conds).order(updated_at: :desc).page(params[:page]).per(params[:limit])
		else
      orders = Order.includes(extra_info).where(conds).order(updated_at: :desc).page(params[:page]).per(params[:limit])
		end

		render json: {status: :success, list: orders.map(&:to_hash), total: orders.total_count}
	end

	# 订单创建／一键下单
	#
	# Params
	# 	access_token: [String] authenication_token
	# 	id: [integer] clue_id
	# 	order[expected_square]: [String] 预估面积
	# 	order[total]: [String] 预估价格
	# 	order[booking_date]: [String] 预约测量时间
	# 	order[cgj_customer_service_id]: [String] 指定测量师傅
	# 	order[measure_master]: [String] 测量师傅名字
	# 	order[cgj_company_id]: [Integer] 品牌商ID
	# 	order[material]: [String] 材料名称
	# 	order[material_id]: [Integer] 材料ID
	#   order[introducer_name]: [String] 介绍人姓名
	# 	order[introducer_tel]: [String] 介绍人手机
	# 	order[region_id]: [Integer] 所属渠道
	# 	order[estimated_total]: [Float] 预估产品价格
	# 	order[store_id]: [Integer] 所属门店
	# 	order[is_sync]: [Boolean] 是否同步窗管家true|false
	# 	customer[name]: [String] 客户名称
	# 	customer[tel]: [String] 手机号
	# 	customer[province]: [String] 省
	# 	customer[city]: [String] 市
	# 	customer[area]: [String] 区
	# 	customer[street]: [String] 街道
	# Return
	# 	status: [String] success
	# 	msg: [String] 创建成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos	
	def create
		raise '企业用户无法下单' if @current_user.account.type == 'Account'
		
		order = Order.new(order_params.merge(owner_params))
		customer = Customer.find_or_initialize_by(tel: params[:customer][:tel])
		customer.attributes = customer.new_record? ? customer_params.merge(owner_params) : customer_params.merge(owner_params).merge(id: customer.id)
	  
	  # 介绍人生成，执行介绍人反利，销售提成
		unless order.introducer_tel.blank?
			introducer = User.get_or_gen_introducer(order.introducer_tel, order.introducer_name, order.account_id)
			order.introducer_id = introducer.id
		end
		
		if customer.save
			order.customer = customer
			order.workflow_state = 'appointed_measurement'
			# order.is_sync = params[:order][:is_sync] == 'true' ? true : false
			order.is_sync = true
			if order.save
				order.sync_cgj if @current_user.cgj_user_id && order.is_sync
				render json: {status: :success, msg: '创建成功'}
			else
				render json: {status: :failed, msg: order.errors.messages.values.first}
			end
		else
			render json: {status: :failed, msg: customer.errors.messages.values.first}
		end 

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

	# 更新产品预估价格
	#
	# Params
	# 	access_token: [String] authenication_token
	#   id: [Integer] ID
	# 	estimated_total: [Float] 产品预估价
	# Return
	# 	status: [String] success
	# 	msg: [String] 更新成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos	
	def update_estimated_total
		raise '您无权操作' unless @current_user == @order.user
		if @order.update_attributes(estimated_total: params[:estimated_total])
			# gen log
			Logs::Order.create(method: 'update_estimated_total', p_hash: params, user_id: @current_user.id, order_id: @order.id)
			render json: {status: :success, msg: '更新成功'}
    else
    	render json: {status: :failed, msg: @order.errors.messages.values.first}
		end
		rescue => e
			render json: {status: :failed, msg: e.message}
	end

	# 更新返利点
	#
	# Params
	# 	access_token: [String] authenication_token
	#   id: [Integer] IDal
	# 	rebate: [Float] 返利百分比
	# Return
	# 	status: [String] success
	# 	msg: [String] 更新成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos	
	def update_rebate
		if @current_user.role == 'admin' && @account == @order.account
		else
			raise '您无权操作'
		end

		if @order.update_attributes(rebate: params[:rebate])
			# gen log
			Logs::Order.create(method: 'rebate', p_hash: params, user_id: @current_user.id, order_id: @order.id)
			render json: {status: :success, msg: '更新成功'}
    else
    	render json: {status: :failed, msg: @order.errors.messages.values.first}
		end
		rescue => e
			render json: {status: :failed, msg: e.message}
	end

  def upload_file
    @order = Order.find_by(id: params[:id])
    render json: {status: :failed, msg: "无效"} and return unless @order
    o = @order.pictures.new(pictures_params)
    if o.save
      Cgj.update_order(@order.serial_number, {pictures: {image: o.url, image_type:"saler_pictures"}})
      render json: {msg: "ok", status: :success, order: @order.to_hash}
    else
      render json: {msg: "失败", status: "failed"}
    end
  end

	# 搜索师傅
	#
	# Params
	# 	access_token: [String] authenication_token
	#   keyword: [String] keyword
	# Return
	# 	status: [String] success
	# 	msg: [String] 
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos	
	def fetch_users
		surveyors = JSON(Cgj.fetch_users(params[:keyword]))["users"].collect{|_hash| {id: _hash["id"], name: _hash["real_name"]}}
	
		render json: {status: :success, surveyors: surveyors}
	end

	def destroy
	end

  def delete_pictures
    p = Picture.find_by(id: params[:picture_id])
    render json: {msg: "无效的 id", status: "failed"} and return unless p
    p.delete
    render json: {msg: :ok, status: "success"}
  end

  def check_order
    order = Order.find_by(id: params[:id])
    ok, result = order.pay_order(@current_user)
    if ok
      render json: {msg: :ok, order: order.to_hash, status: "success"}
    else
      render json: {msg: result, status: "failed"}
    end
  end

	private

	def order_params
		params[:order].permit(:expected_square, :rate, :booking_date, :cgj_company_id, :material, :material_id, :introducer_name, :introducer_tel, :region_id, :store_id, :total, :estimated_total, :cgj_customer_service_id, :measure_master)
	end

	def customer_params
		params[:customer].permit(:name, :tel, :province, :city, :area, :street)
	end

	def owner_params
		{user_id: @current_user.id, account_id: @current_user.account_id}
	end

  def pictures_params
    params.permit(:image).tap do |white|
      white[:image_type] = "saler_pictures"
    end
  end

	def get_order
		@order = Order.find(params[:id])
		raise 'not found' unless @order
		rescue => e
			render json: {status: :failed, msg: e.message}
	end

end
